package cn.fl.capital.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.*;
import cn.fl.capital.constant.CapAdvBatchConstant;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;

import cn.fl.capital.condition.CapAdvBatchQueryCondition;
import cn.fl.capital.dto.CapAdvBatchDTO;
import cn.fl.capital.service.ICapAdvBatchService;
import cn.fl.capital.vo.CapAdvBatchVO;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;

import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.constant.SysLogConstant;

/**
 * @Description: 垫款批次表 控制层
 */
@Controller
@RequestMapping("/capital/capAdvBatch")
public class CapAdvBatchController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CapAdvBatchController.class);
	
	/**
	 * CapAdvBatch 服务层BEAN
	 */
	@Autowired
	private ICapAdvBatchService capAdvBatchService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载CapAdvBatch列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capAdvBatch/capAdvBatchList");
		//垫款/核销方式1.垫款 2.核销
		String advTypCd = request.getParameter("advTypCd");
		mav.addObject("advTypCd",advTypCd);
		if(StringUtils.isNotBlank(advTypCd)&& CapAdvBatchConstant.CODE_ADV_TYP_CD_2.equals(advTypCd)){
		    mav.setViewName("capital/capAdvBatch/capRvtBatchList");
        }
		mav.addObject("advWayCdList", JSON.toJSONString(this.capAdvBatchService.searchCdList(CapAdvBatchConstant.CODE_ADV_WAY_CD)));
		return mav;
	}
	
	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toAddPage", "加载CapAdvBatch Add页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capAdvBatch/capAdvBatchModify");
		//this.prepare(request,mav);
		return mav;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toModifyPage", "加载CapAdvBatch Modify页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView mav = new ModelAndView("capital/capAdvBatch/capAdvBatchModify");
		//this.prepare(request,mav);
		
		String id=request.getParameter("id");
		CapAdvBatchVO capAdvBatchVO = this.capAdvBatchService.selectById(Long.valueOf(id));
        mav.addObject("capAdvBatchVO", capAdvBatchVO);
		return mav;
	}

    /**
     * 垫款、核销详情页
     */
    @RequestMapping(value = "/toDtlPage.do", method = { RequestMethod.GET, RequestMethod.POST })
    public ModelAndView toDtlPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载CapAdvBatch详情页面.",CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvBatch/capAdvBatchDtl");
        //this.prepare(request,mav);

        String id = request.getParameter("id");
        String advTypCd = request.getParameter("advTypCd");
        CapAdvBatchVO capAdvBatchVO = this.capAdvBatchService.selectById(Long.valueOf(id));
        mav.addObject("capAdvBatchVO", capAdvBatchVO);
        return mav;
    }

	//加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request,ModelAndView mav){
    	
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initCapAdvBatchList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CapAdvBatchQueryCondition qc = new CapAdvBatchQueryCondition();
		String crtTmMin = request.getParameter("crtTmMin");
        String crtTmMax = request.getParameter("crtTmMax");
        String minAdvAmt = request.getParameter("minAdvAmt");
        String maxAdvAmt = request.getParameter("maxAdvAmt");
        String minAdvClAmt = request.getParameter("minAdvClAmt");
        String maxAdvClAmt = request.getParameter("maxAdvClAmt");
		String ruleNm = request.getParameter("ruleNm");
		String advTypCd = request.getParameter("advTypCd");
		String advWayCd = request.getParameter("advWayCd");
		if(StringUtils.isNotBlank(crtTmMin)){
		    qc.setCrtTmMin(crtTmMin);
        }
        if(StringUtils.isNotBlank(crtTmMax)){
            qc.setCrtTmMax(crtTmMax);
        }
        if(StringUtils.isNotEmpty(minAdvAmt)){
            qc.setMinAdvAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(minAdvAmt)));
        }
        if(StringUtils.isNotEmpty(maxAdvAmt)){
            qc.setMaxAdvAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(maxAdvAmt)));
        }
        if(StringUtils.isNotEmpty(minAdvClAmt)){
            qc.setMinAdvClAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(minAdvClAmt)));
        }
        if(StringUtils.isNotEmpty(maxAdvClAmt)){
            qc.setMaxAdvClAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(maxAdvClAmt)));
        }
        if(StringUtils.isNotBlank(ruleNm)){
            qc.setRuleNm(ruleNm);
        }
        if(StringUtils.isNotBlank(advTypCd)){
            qc.setAdvTypCd(advTypCd);
        }
        if(StringUtils.isNotBlank(advWayCd)){
            qc.setAdvWayCd(advWayCd);
        }

        qc.setSendStsCd(CapAdvBatchConstant.CODE_SEND_STS_CD_2);
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initCapAdvBatchList", "初始化CapAdvBatch列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		Pager pager = this.capAdvBatchService.searchListPage(page);
		List<CapAdvBatchVO> list = (List<CapAdvBatchVO>) pager.getResultList();
		ListPageVO<CapAdvBatchVO> listPage = new ListPageVO<CapAdvBatchVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeCapAdvBatchByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapAdvBatchByIds", "删除CapAdvBatch数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }
		
		try {
			boolean success = this.capAdvBatchService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeCapAdvBatchByIds", "删除CapAdvBatch数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeCapAdvBatchByIds", "删除CapAdvBatch数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "removeCapAdvBatchByIds", "删除CapAdvBatch数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeCapAdvBatchByIds", "删除CapAdvBatch数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getCapAdvBatchById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getCapAdvBatchById", "获取CapAdvBatch数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			CapAdvBatchVO vo = this.capAdvBatchService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getCapAdvBatchById", "获取CapAdvBatch数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getCapAdvBatchById", "获取CapAdvBatch数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getCapAdvBatchById", "获取CapAdvBatch数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getCapAdvBatchById", "获取CapAdvBatch数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addCapAdvBatch(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		CapAdvBatchVO entity = null;//获取参数
		try {
			entity = this.getRequestParamForCapAdvBatch(request);//获取参数
			Long id = this.capAdvBatchService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addCapAdvBatch", "新增CapAdvBatch数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "addCapAdvBatch", "新增CapAdvBatch数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "addCapAdvBatch", "新增CapAdvBatch数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyCapAdvBatch(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		CapAdvBatchVO entity = null;
		try {
			entity = this.getRequestParamForCapAdvBatch(request);
			if(entity.getId()==null){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
				BaseLogUtils.info(logger, "modifyCapAdvBatch", "修改CapAdvBatch信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
				return result;
			}

			boolean success = this.capAdvBatchService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyCapAdvBatch", "修改CapAdvBatch数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modifyCapAdvBatch", "修改CapAdvBatch数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.info(logger, "modifyCapAdvBatch", "修改CapAdvBatch数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR+ex.getMessage());
			BaseLogUtils.error(logger, "modifyCapAdvBatch", "修改CapAdvBatch数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 获取请求参数
	 * @param request 请求
	 * @return 
	 */
	private CapAdvBatchVO getRequestParamForCapAdvBatch(HttpServletRequest request) throws BaseException{
		//获取参数
		String id = request.getParameter("id");//主键
		String batchNo = request.getParameter("batchNo");//批次号（流水号）
		String advRuleId = request.getParameter("advRuleId");//垫款规则ID（垫款规则表ID）
		String advTtlAmt = request.getParameter("advTtlAmt");//垫款/核销总金额
		String advTypCd = request.getParameter("advTypCd");//垫款/核销方式CAP0037：1.自动 2.手动

		//验证参数并赋值
		CapAdvBatchVO entity = new CapAdvBatchVO();
 		//entity.setBatchNo(batchNo);//批次号（流水号）
 		//entity.setAdvRuleId(advRuleId);//垫款规则ID（垫款规则表ID）
 		//entity.setAdvTtlAmt(advTtlAmt);//垫款/核销总金额
 		//entity.setAdvTypCd(advTypCd);//垫款/核销方式CAP0037：1.自动 2.手动
	
//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

		Date tm=new Date();
		if (StringUtils.isNotBlank(id)) {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(tm);
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		}else{
			entity.setCrtTm(tm);
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			//entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
		}
		
		return entity;
	}
}

